package com.topisv.tms.rest.entity.md;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import com.topisv.tms.rest.entity.md.request.TransferData;

public class JAXBDemo2 {
	static String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"  
	+"<TransferData>"
	+"<TransferSubject>"
		+"	<Sender>paiu</Sender>"
			+"<Receiver>md</Receiver>"
			+"<DocumentType>2</DocumentType>"
			+"<DataGenerationDate>2014-11-28 09:50:01</DataGenerationDate>"
	+"<TransferFileID>20141128095001597</TransferFileID>"
	+"<Sign></Sign>"
	+"</TransferSubject>"
		+"<TransferBody>"
	+"<annto_order>"
	+"<cust_ord_no>1233</cust_ord_no>"
	+"<plan_out_time>214-1-1 2:9:2</plan_out_time>"
	+"</annto_order>"
+"		</TransferBody>"
+"</TransferData>";
	public static void main(String[] args) throws JAXBException {
		//type1();
		type2();
	}
	
	public static void type1(){
		TransferData c = tranferFromXml();
				tranferFromBean(c);
	}
	public static void type2() throws JAXBException{
		JAXBContext context = JAXBContext.newInstance(TransferData.class);
		TransferData c = unmarshal(xml, context, TransferData.class);
		System.out.println(marshal(context, c));
	}
	
	public static TransferData tranferFromXml(){
		return JAXB.unmarshal(new StringReader(xml), TransferData.class);
	}
	public static void tranferFromBean(TransferData customer){
		JAXB.marshal(customer, System.out);
	}

	public static <T> String marshal(JAXBContext context, final T chart) throws JAXBException {
		final Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
		marshaller.setProperty("com.sun.xml.bind.xmlDeclaration",false);
		final StringWriter stringWriter = new StringWriter();

		marshaller.marshal(chart, stringWriter);

		String chartXml = stringWriter.toString();
		return chartXml;
	}

	public static <T> T unmarshal(String template, JAXBContext context, Class<T> clazz) throws JAXBException {

		final Unmarshaller unmarshaller = context.createUnmarshaller();
		final JAXBElement<T> chart = unmarshaller.unmarshal(new StreamSource(new StringReader(template)), clazz);
		return chart.getValue();
	}
	
}
